package org.example.classtopia.Service.Impl;

import lombok.extern.slf4j.Slf4j;
import org.example.classtopia.Common.Result.Result;
import org.example.classtopia.Mapper.UserMassageMapper;
import org.example.classtopia.Mapper.PostMapper;
import org.example.classtopia.Mapper.ResourceMapper;
import org.example.classtopia.Mapper.UserMapper;
import org.example.classtopia.Model.Entity.UserMessage;
import org.example.classtopia.Model.Entity.Post;
import org.example.classtopia.Model.Entity.Resource;
import org.example.classtopia.Model.Entity.User;
import org.example.classtopia.Repository.MessageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@Component
@Slf4j
public class UserMessageService {
    private final MessageRepository messageRepository;

    @Autowired
    private UserMassageMapper userMassageMapper;
    @Autowired
    private PostMapper postMapper;
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserMassageMapper userMessageMapper; // 你的MyBatis Mapper或Repository

    public UserMessageService(MessageRepository messageRepository, UserMassageMapper userMassageMapper) {
        this.messageRepository = messageRepository;
        this.userMassageMapper = userMassageMapper;
    }

    /**
     * 根据用户ID和消息状态获取用户消息列表
     * @param userId 用户ID
     * @param page 页码，从0开始
     * @param size 每页大小
     * @param type 消息状态类型：0-查看未读消息，1-查看已读消息，-1-查看全部消息
     * @return 分页的用户消息列表
     */
    public Page<UserMessage> getUserMessageByUserId(Long userId, int page, int size, int type){
        PageRequest pageRequest = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "time"));
        Page<UserMessage> msgPage;
        // 根据type参数决定查询策略
        switch (type) {
            case 0:
                // 查看未读消息
                log.info("查询用户ID: {} 的未读消息，页码: {}, 页大小: {}", userId, page, size);
                msgPage = messageRepository.findByUserIdAndIsRead(userId, (short) 0, pageRequest);
                break;
            case 1:
                // 查看已读消息
                log.info("查询用户ID: {} 的已读消息，页码: {}, 页大小: {}", userId, page, size);
                msgPage = messageRepository.findByUserIdAndIsRead(userId, (short) 1, pageRequest);
                break;
            case -1:
            default:
                // 查看全部消息
                log.info("查询用户ID: {} 的所有消息，页码: {}, 页大小: {}", userId, page, size);
                msgPage = messageRepository.findByUserId(userId, pageRequest);
        }
        // 为每条消息动态赋值postName和resourceName
        msgPage.forEach(msg -> {
            if (msg.getPostId() != null) {
                Post post = postMapper.selectPostById(msg.getPostId());
                if (post != null) msg.setPostName(post.getTitle());
            }
            if (msg.getResourceId() != null) {
                Resource res = resourceMapper.selectResourceById(msg.getResourceId());
                if (res != null) msg.setResourceName(res.getTitle());
            }
        });
        return msgPage;
    }

    /**
     * 根据用户ID获取用户消息列表（保留原方法以保持向后兼容）
     * @param userId 用户ID
     * @param page 页码，从0开始
     * @param size 每页大小
     * @return 分页的用户消息列表
     */
    public Page<UserMessage> getUserMessageByUserId(Long userId, int page, int size){
        return getUserMessageByUserId(userId, page, size, -1);
    }

    /**
     * 更新用户消息状态为已读
     * @param Id 消息ID
     * @return 操作结果
     */
    public Result<String> updateUserMessageStatus(Long Id){
        try{
            userMassageMapper.UpdateUserMessageStatus(Id);
            return Result.success("修改消息已读状态成功！");
        }
        catch (Exception e){
            return Result.error(400,"修改已读消息状态失败！");
        }
    }

    /**
     * 将用户全部未读消息设为已读
     * @param userId 用户ID
     * @return 操作结果
     */
    public Result<String> markAllMessagesAsRead(Long userId) {
        try {
            userMassageMapper.UpdateAllUserMessagesStatus(userId);
            log.info("成功将用户ID: {} 的全部未读消息标记为已读", userId);
            return Result.success("全部消息已设为已读！");
        } catch (Exception e) {
            log.error("批量标记用户ID: {} 的消息为已读失败: {}", userId, e.getMessage());
            return Result.error(400, "批量标记消息为已读失败！");
        }
    }

    /**
     * 判断用户是否有未读消息
     * @param userId 用户ID
     * @return 是否有未读消息（true/false）
     */
    public Result<Boolean> hasUnreadMessages(Long userId) {
        try {
            int count = userMassageMapper.countUnreadMessages(userId);
            return Result.success(count > 0);
        } catch (Exception e) {
            log.error("查询用户未读消息失败: {}", e.getMessage());
            return Result.error(500, "查询未读消息失败");
        }
    }

    /**
     * 判断用户是否有未读消息（可按消息类型筛选）
     * @param userId 用户ID
     * @param messageType 消息类型：-1-全部，0-系统消息，1-点赞评论
     * @return 是否有未读消息（true/false）
     */
    public Result<Boolean> hasUnreadMessages(Long userId, int messageType) {
        try {
            int count;
            if (messageType == -1) {
                // 全部类型
                count = userMassageMapper.countUnreadMessages(userId);
            } else if (messageType == 0) {
                // 系统消息（假设 message_type = 'system'）
                count = userMassageMapper.countUnreadMessagesByType(userId, "system");
            } else if (messageType == 1) {
                // 点赞评论（假设 message_type = 'postLike' 或 'comment'）
                count = userMassageMapper.countUnreadMessagesByTypes(userId, new String[]{"postLike", "comment"});
            } else {
                return Result.error(400, "消息类型参数错误");
            }
            return Result.success(count > 0);
        } catch (Exception e) {
            log.error("查询用户未读消息失败: {}", e.getMessage());
            return Result.error(500, "查询未读消息失败");
        }
    }

    /**
     * 根据用户ID、消息状态和消息类型获取用户消息列表
     * @param userId 用户ID
     * @param page 页码，从0开始
     * @param size 每页大小
     * @param type 消息状态类型：0-查看未读消息，1-查看已读消息，-1-查看全部消息
     * @param messageType 消息类型：0-系统消息，1-点赞/评论/资源点赞消息
     * @return 分页的用户消息列表
     */
    public Page<UserMessage> getUserMessageByUserId(Long userId, int page, int size, int type, int messageType){
        PageRequest pageRequest = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "time"));
        Page<UserMessage> msgPage;

        // 根据messageType确定消息类型条件
        String[] targetTypes;
        if (messageType == 0) {
            // 系统消息
            targetTypes = new String[]{"system"};
            log.info("查询用户ID: {} 的系统消息，状态: {}, 页码: {}, 页大小: {}", userId, type, page, size);
        } else if (messageType == 1) {
            // 点赞、评论、资源点赞消息
            targetTypes = new String[]{"postLike", "comment", "resourceLike"};
            log.info("查询用户ID: {} 的点赞/评论/资源点赞消息，状态: {}, 页码: {}, 页大小: {}", userId, type, page, size);
        } else {
            throw new IllegalArgumentException("消息类型参数错误");
        }

        // 根据type和messageType组合查询
        switch (type) {
            case 0:
                // 查看未读消息
                msgPage = messageRepository.findByUserIdAndIsReadAndMessageTypeIn(userId, (short) 0, targetTypes, pageRequest);
                break;
            case 1:
                // 查看已读消息
                msgPage = messageRepository.findByUserIdAndIsReadAndMessageTypeIn(userId, (short) 1, targetTypes, pageRequest);
                break;
            case -1:
            default:
                // 查看全部消息
                msgPage = messageRepository.findByUserIdAndMessageTypeIn(userId, targetTypes, pageRequest);
        }

        // 为每条消息动态赋值postName和resourceName
        msgPage.forEach(msg -> {
            if (msg.getPostId() != null) {
                Post post = postMapper.selectPostById(msg.getPostId());
                if (post != null) msg.setPostName(post.getTitle());
            }
            if (msg.getResourceId() != null) {
                Resource res = resourceMapper.selectResourceById(msg.getResourceId());
                if (res != null) msg.setResourceName(res.getTitle());
            }
        });
        return msgPage;
    }

    /**
     * 根据用户名统计三种类型的未读消息数量
     * @param username 用户名（email）
     * @return 各类型未读消息数量（postLike/comment/system）
     */
    public Result<Map<String, Integer>> getUnreadMessageCountByType(String username) {
        try {
            // 1. 查找用户
            User user = userMapper.FindByEmail(username);
            if (user == null) {
                return Result.error(404, "用户不存在");
            }
            Long userId = user.getId();
            // 2. 统计三类未读消息数量
            int postLikeCount = userMassageMapper.countUnreadMessagesByType(userId, "postLike");
            int commentCount = userMassageMapper.countUnreadMessagesByType(userId, "comment");
            int systemCount = userMassageMapper.countUnreadMessagesByType(userId, "system");
            Map<String, Integer> result = new java.util.HashMap<>();
            result.put("postLike", postLikeCount);
            result.put("comment", commentCount);
            result.put("system", systemCount);
            return Result.success(result);
        } catch (Exception e) {
            log.error("统计未读消息数量失败: {}", e.getMessage());
            return Result.error(500, "统计未读消息数量失败");
        }
    }

    /**
     * 根据用户ID统计三种类型的未读消息数量
     * @param userId 用户ID
     * @return 各类型未读消息数量（postLike/comment/system）
     */
    public Result<Map<String, Integer>> getUnreadMessageCountByType(Long userId) {
        try {
            int postLikeCount = userMassageMapper.countUnreadMessagesByType(userId, "postLike");
            int commentCount = userMassageMapper.countUnreadMessagesByType(userId, "comment");
            int systemCount = userMassageMapper.countUnreadMessagesByType(userId, "system");
            int resourceLikeCount = userMassageMapper.countUnreadMessagesByType(userId, "resourceLike");
            Map<String, Integer> result = new java.util.HashMap<>();
            result.put("postLike", postLikeCount);
            result.put("comment", commentCount);
            result.put("system", systemCount);
            result.put("resourceLike", resourceLikeCount);
            return Result.success(result);
        } catch (Exception e) {
            log.error("统计未读消息数量失败: {}", e.getMessage());
            return Result.error(500, "统计未读消息数量失败");
        }
    }

    public void saveMessage(UserMessage msg) {
        userMessageMapper.InsertUserMessage(msg);
    }

    /**
     * 根据用户ID获取用户实体
     * @param userId 用户ID
     * @return User实体，找不到返回null
     */
    public User getUserById(Long userId) {
        if (userId == null) {
            log.warn("getUserById传入了null的userId");
            return null;
        }
        try {
            return userMapper.findById(userId);
        } catch (Exception e) {
            log.error("通过userId查询用户失败，userId={}: {}", userId, e.getMessage(), e);
            return null;
        }
    }
}
